<?php
/**
 * Controller_Ajax_Common
 *
 * Класс Controller_Ajax_Common отвечает за действия, общие для всего сайта
 *
 * @author Гринько Виталий <vitalygrinko@gmail.com>
 * @version 1.0
 */
class Controller_Ajax_Common extends Controller_Ajax {
  
  public $callEmail = 'perlaws@gmail.com';
  public $quickRequestEmail = 'perlaws@bitbybit.ru';
  
	public function __construct(&$arrRequest) {
	  parent::__construct($arrRequest, $arrRequest[2] != 'upload_temp_avatar');
		switch ($this->arrRequest[2]) {
		  case 'delete_temp_avatar': // Получение календаря для профайла гида
        $this->getActionDeleteTempAvatar(); // POST
		    break;
      case 'upload_temp_avatar':
				$this->getActionUploadTempAvatar();
			  break;
		  case 'call_request': // Запрос обратного звонка
        $this->getActionCallRequest(); // POST
		    break;
		  case 'quick_request': // Быстрый заказ
        $this->getActionQuickRequest(); // POST
		    break;
		  case 'status_search_form': // Статус формы поиска
        $this->getActionGetFormStatus(); // POST
		    break;
			default: $this->show404Error();
		}
	}

	/**
	 * Метод осуществляет обработку формы запроса обратного звонка
	 *
	 */
	public function getActionCallRequest() {
	  $objSession = User_Session::instance();
	  if (isset($_POST['Call'])) {
  	  $arrCall = $_POST['Call'];
      $name = isset($arrCall['name']) ? Service_Function::absolutelyEscapeString($arrCall['name']) : '';
      $name = trim($name);
      $date = isset($arrCall['date']) ? Service_Function::absolutelyEscapeString($arrCall['date']) : '';
      $time = isset($arrCall['time']) ? (int)$arrCall['time'] : 0;
      $phone = isset($arrCall['phone']) ? Service_Function::absolutelyEscapeString($arrCall['phone']) : '';
      $e_mail = isset($arrCall['e_mail']) ? Service_Function::absolutelyEscapeString($arrCall['e_mail']) : '';
      $comments = isset($arrCall['comments']) ? Service_Function::absolutelyEscapeString($arrCall['comments']) : '';
      $captcha = isset($arrCall['kaptcha']) ? Service_Function::absolutelyEscapeString($arrCall['kaptcha']) : '';
      
      $arrErrors = array(); //массив с ошибками
      if (!strlen($name)) $arrErrors[] = array('selector' => '#Call_name', 
                                               'text' => array('You have not specified your name'));
      if (!preg_match("/^\d{2}.\d{2}.\d{4}$/", $date)) $arrErrors[] = array('selector' => '#Call_date', 
                                                                            'text' => array('You have not specified the date you are ready to talk with our representative'));
      if ($time < 0 || $time > 2) $arrErrors[] = array('selector' => '#Call_time', 
                                                       'text' => array('Wrong time format'));
      if (!preg_match("/^\d{3} \(\d{3}\) \d{3}-\d{4}$/", $phone)) $arrErrors[] = array('selector' => '#Call_phone', 
                                                                                       'text' => array('Wrong phone format'));
      $mailRegexp ="/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/";
      if (!preg_match($mailRegexp, $e_mail)) $arrErrors[] = array('selector' => '#Call_e_mail', 
                                                                  'text' => array('Wrong E-mail format'));
      if (empty($captcha) || $objSession->__get('keystring') != $captcha) $arrErrors[] = array('selector' => '#Call_kaptcha', 
                                                                                               'text' => array('Wrong security code'));
      if (sizeof($arrErrors)) { // Если есть ошибки
        $arrResult = array('result' => 'error', 'exceptions' => $arrErrors);
      }
      else { //ошибок нет
        //отправляем письмо на предопределённый адрес
        $html = $name . '<br />' .
                $date . ' (' . $time . ')' . '<br />' .
                $phone . '<br />' .
                $e_mail . '<br />' .
                $comments;
        $m = new Service_Mail(
          '[RussianRailways.com] New Call Request',
          '',
          $html,
          '',
          array($this->callEmail)
        );
        //$m->send();
        $arrResult = array('result' => 'ok');
      }
	  } else $arrResult = array('result' => 'error', 'exceptions' => array('Data loading error'));
		$objJSON = new Service_JSON();
		echo $objJSON->encode($arrResult);
	}
	/**
	 * Метод осуществляет обработку формы быстрого заказа
	 *
	 */
	public function getActionQuickRequest() {
	  $objSession = User_Session::instance();
    if (isset($_POST['QuickRequest'])) {
  	  $arrQuickRequest = $_POST['QuickRequest'];
      $name = isset($arrQuickRequest['name']) ? Service_Function::absolutelyEscapeString($arrQuickRequest['name']) : '';
      $name = trim($name);
      $date = isset($arrQuickRequest['date']) ? Service_Function::absolutelyEscapeString($arrQuickRequest['date']) : '';
      $departure = isset($arrQuickRequest['departure']) ? Service_Function::absolutelyEscapeString($arrQuickRequest['departure']) : '';
      $arrival = isset($arrQuickRequest['arrival']) ? Service_Function::absolutelyEscapeString($arrQuickRequest['arrival']) : '';
      $phone = isset($arrQuickRequest['phone']) ? Service_Function::absolutelyEscapeString($arrQuickRequest['phone']) : '';
      $e_mail = isset($arrQuickRequest['e_mail']) ? Service_Function::absolutelyEscapeString($arrQuickRequest['e_mail']) : '';
      $comments = isset($arrQuickRequest['comments']) ? Service_Function::absolutelyEscapeString($arrQuickRequest['comments']) : '';
      $captcha = isset($arrQuickRequest['kaptcha']) ? Service_Function::absolutelyEscapeString($arrQuickRequest['kaptcha']) : '';
      
      $arrErrors = array(); //массив с ошибками
      if (!strlen($name)) $arrErrors[] = array('selector' => '#QuickRequest_name', 
                                               'text' => array('You have not specified your name'));
      if (!preg_match("/^\d{2}.\d{2}.\d{4}$/", $date)) $arrErrors[] = array('selector' => '#QuickRequest_date', 
                                                                            'text' => array('You have not specified the date you are ready to talk with our representative'));
      if (!strlen($departure)) $arrErrors[] = array('selector' => '#QuickRequest_departure', 
                                               'text' => array('You have not specified the place of departure'));
      if (!strlen($arrival)) $arrErrors[] = array('selector' => '#QuickRequest_arrival', 
                                               'text' => array('You have not specified the place of arrival'));
      if (!preg_match("/^\d{3} \(\d{3}\) \d{3}-\d{4}$/", $phone)) $arrErrors[] = array('selector' => '#QuickRequest_phone', 
                                                                                       'text' => array('Wrong phone format'));
      $mailRegexp ="/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,3})|(aero|coop|info|museum|name))$/";
      if (!preg_match($mailRegexp, $e_mail)) $arrErrors[] = array('selector' => '#QuickRequest_e_mail', 
                                                                  'text' => array('Wrong E-mail format'));
      if (empty($captcha) || $objSession->__get('keystring') != $captcha) $arrErrors[] = array('selector' => '#QuickRequest_kaptcha', 
                                                                                               'text' => array('Wrong security code'));

      if (sizeof($arrErrors)) { // Если есть ошибки
        $arrResult = array('result' => 'error', 'exceptions' => $arrErrors);
      }
      else { //ошибок нет
        //отправляем письмо на предопределённый адрес
        $html = $name . '<br />' .
                $date . '<br />' .
                'Departure: ' . $departure . '<br />' .
                'Arrival: ' . $arrival . '<br />' .
                $phone . '<br />' .
                $e_mail . '<br />' .
                $comments;
        $m = new Service_Mail(
          '[RussianRailways.com] New Quick Request',
          '',
          $html,
          '',
          array($this->quickRequestEmail)
        );
        //$m->send();
        $arrResult = array('result' => 'ok');
      }
	  } else $arrResult = array('result' => 'error', 'exceptions' => array('Data loading error'));

		$objJSON = new Service_JSON();
		echo $objJSON->encode($arrResult);
	}
	
	/**
	 * Действие - удаление загруженного аватара
	 *
	 */
	public function getActionDeleteTempAvatar() {
		if (isset($_POST['avatar'])) $avatar = Service_Function::absolutelyEscapeString($_POST['avatar']);
		if (file_exists(ABSPATH . 'content/images/essence/user/tmp/s_' . $avatar)) unlink(ABSPATH . 'content/images/essence/user/tmp/s_' . $avatar);
		if (file_exists(ABSPATH . 'content/images/essence/user/tmp/m_' . $avatar)) unlink(ABSPATH . 'content/images/essence/user/tmp/m_' . $avatar);
		if (file_exists(ABSPATH . 'content/images/essence/user/tmp/b_' . $avatar)) unlink(ABSPATH . 'content/images/essence/user/tmp/b_' . $avatar);
		echo "{";
		echo '"result": "OK"';
		echo "}";
	}
	
	/**
	 * Действие - "Загрузка аватара"
	 *
	 */
	public function getActionUploadTempAvatar() {
		$error = '';
		$msg = '';
		$image = new Image('pic', $_FILES['pic'], array('folder' => 'essence/user/tmp/', 'square' => true));
		$image->addArrSize(60, 60, 's_');//формируем дополнительное изображение нужного размера
		$image->addArrSize(120, 120, 'm_');//формируем дополнительное изображение нужного размера
		$image->addArrSize(200, 200, 'b_');//формируем дополнительное изображение нужного размера
		$image->save();
		$imgServerPath = IMAGES . 'essence/user/tmp/s_' . $image->getImageName();
		$sizes = getimagesize($imgServerPath);
		echo "{";
		echo "error: '" . $error . "',\n";
		echo "pic_width: '" . $sizes[0] . "',\n";
		echo "pic_height: '" . $sizes[1] . "',\n";
		echo "pic_file: '" . $image->getImageName() . "'\n";
		
		echo "}";
	}

	/**
	 * Сохранение статуса формы поиска
	 *
	 */
	public function getActionGetFormStatus() {
    $objSession = User_Session::instance();
    User_Variable::addVariableValue($objSession->getUserId(), 'search_form_visibility', $_POST['selected']);
	}
	
}
?>